package com.duesoft.myandroid;

import java.io.File;
import java.util.List;
import java.util.Locale;

import android.R.integer;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.duesoft.myandroid.fragments.ArticleFragment;
import com.duesoft.myandroid.fragments.PictureFragment;

public class MainActivity extends Activity implements
		ArticleFragment.OnArticleSelectedListener {

	public final static String EXTRA_MESSAGE = "com.duesoft.myandroid.MESSAGE";

	public final static String INPUT_MESSAGE = "com.duesoft.myandorid.INPUT_MESSAGE";

	public final static int TAKE_PICTURE_REQUEST_CODE = 1;

	public final static int START_BROWSER_REQUEST_CODE = 2;

	private Camera mCamera;

	private Uri mImagUri;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// multiple language supported, must be call it before setContentView
		// setUILang(Locale.CHINA);
		setContentView(R.layout.activity_main);
		
		// load state
		if (savedInstanceState != null) {

		} else {

		}

		// start activity from other app
		handleStartFromOtherApp();

		// dynamic load fragment
		FrameLayout frameLayout = (FrameLayout) findViewById(R.id.fragment_container);
		if (frameLayout != null) {
			ArticleFragment articleFragment = new ArticleFragment();

			FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
			fragmentTransaction.add(R.id.fragment_container, articleFragment);
			fragmentTransaction.commit();
		}

		setButtonShowClickEvent();
		setButtonCaptureClickEvent();
		setFragmentButtonClickEvent();
		setButtonMapClickEvent();
	}

	private void handleStartFromOtherApp() {
		// Get the intent that started this activity
		Intent intent = getIntent();
		if (intent == null) {
			return;
		}
		Uri uri = intent.getData();

		// Figure out what to do based on the intent type
		String intentType = intent.getType();
		if (intentType.indexOf("image/") != -1) {
			// Handle intents with image data
			try {
				ContentResolver contentResolver = getContentResolver();
				contentResolver.notifyChange(mImagUri, null);
				
				Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, mImagUri);
				ImageView imageView = (ImageView) findViewById(R.id.imageView1);
				imageView.setImageBitmap(bitmap);
				
				//Create intent to deliver some kind of result data
				Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri"));
				setResult(Activity.RESULT_OK, result);
				//setResult(2); //greater than 0				
			} catch (Exception e) {
				Toast.makeText(this, "Fail to load", Toast.LENGTH_LONG).show();
				Log.e("Camera", e.toString());
			}
		} else if (intentType.equals("text/plain")) {
			// Handle intent with text
		}
		
		finish();	//just call it return to original Activity
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case TAKE_PICTURE_REQUEST_CODE:
			if (resultCode == Activity.RESULT_OK) {
				
				ContentResolver contentResolver = getContentResolver();
				contentResolver.notifyChange(mImagUri, null);

				try {
					Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, mImagUri);
					ImageView imageView = (ImageView) findViewById(R.id.imageView1);
					imageView.setImageBitmap(bitmap);

					Toast.makeText(this, mImagUri.toString(), Toast.LENGTH_LONG).show();
				} catch (Exception e) {
					Toast.makeText(this, "Fail to load", Toast.LENGTH_LONG).show();
					Log.e("Camera", e.toString());
				}
			}
			break;

		default:
			break;
		}
	}

	private void setButtonShowClickEvent() {
		Button buttonShow = (Button) findViewById(R.id.buttonShowInput);
		String sendText = getResources().getString(R.string.send);
		buttonShow.setText(sendText);
		// buttonShow.setText(ResourceUtils.getString(R.string.send));

		buttonShow.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// EditText editText =
				// (EditText)findViewById(R.id.editTextInput);
				// Toast.makeText(v.getContext(), editText.getText().toString(),
				// Toast.LENGTH_LONG).show();
				Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);

				EditText editText = (EditText) findViewById(R.id.editTextInput);
				String message = editText.getText().toString();

				intent.putExtra(EXTRA_MESSAGE, message);

				startActivity(intent);
			}
		});
	}

	private void setButtonCaptureClickEvent() {
		Button buttonCapture = (Button) findViewById(R.id.buttonCapture);
		buttonCapture.setOnClickListener(new View.OnClickListener() {

			// start camera
			public void onClick(View v) {
				// Intent intent = new
				// Intent("android.media.action.STILL_IMAGE_CAMERA");
				File imageFile = new File(Environment.getExternalStorageDirectory(), "pic.jpg");
				mImagUri = Uri.fromFile(imageFile);

				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImagUri);

				startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE);
			}
		});
	}

	private void setButtonMapClickEvent() {
		Button buttonMap = (Button) findViewById(R.id.buttonMap);
		buttonMap.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// Map point based on address
				// Uri location =
				// Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
				// Or map point based on latitude/longitude
				// Uri location = Uri.parse("geo:37.422219,-122.08364?z=14"); //
				// z param is zoom level
				// Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

				// Uri webpage = Uri.parse("http://www.android.com");
				// Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);

				Intent emailIntent = new Intent(Intent.ACTION_SEND);
				// The intent does not have a URI, so declare the "text/plain"
				// MIME type

				// send email
				// emailIntent.setType(HTTP.PLAIN_TEXT_TYPE);
				// emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]
				// {"jon@example.com"}); // recipients
				// emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
				// emailIntent.putExtra(Intent.EXTRA_TEXT,
				// "Email message text");
				// emailIntent.putExtra(Intent.EXTRA_STREAM,
				// Uri.parse("content://path/to/email/attachment"));
				// You can also attach multiple items by passing an ArrayList of
				// Uris

				// calendar
				// Intent calendarIntent = new Intent(Intent.ACTION_INSERT,
				// Events.CONTENT_URI);
				// Calendar beginTime = Calendar.getInstance().set(2012, 0, 19,
				// 7, 30);
				// Calendar endTime = Calendar.getInstance().set(2012, 0, 19,
				// 10, 30);
				// calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,
				// beginTime.getTimeInMillis());
				// calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,
				// endTime.getTimeInMillis());
				// calendarIntent.putExtra(Events.TITLE, "Ninja class");
				// calendarIntent.putExtra(Events.EVENT_LOCATION,
				// "Secret dojo");

				// Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new
				// Uri("content://contacts"));
				// pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user
				// only contacts w/ phone numbers
				// startActivityForResult(pickContactIntent,
				// PICK_CONTACT_REQUEST);

				// Uri uri = Uri.parse("tel:13800138000");
				// Uri uri =
				// Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
				Uri uri = Uri.parse("http://www.android.com");
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);

				int intentCount = getPackageManager().queryIntentActivities(intent, 0).size();
				if (intentCount > 1) {
					String title = getResources().getString(R.string.chooser_title);
					Intent chooser = Intent.createChooser(intent, title);

					startActivity(chooser);
				} else if (intentCount == 1) {
					startActivityForResult(intent, START_BROWSER_REQUEST_CODE);
				} else {
					Toast.makeText(getApplicationContext(), "No app to use", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	private void setFragmentButtonClickEvent() {
		Button buttonFragment = (Button) findViewById(R.id.buttonFragment);
		buttonFragment.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				// dynamic replace fragment by another fragment
				// PictureFragment pictureFragment = new PictureFragment();
				// Bundle args = new Bundle();
				// args.putString(PictureFragment.ARG_TEXT, "10");
				//
				// pictureFragment.setArguments(args);
				//
				// FragmentTransaction fragmentTransaction =
				// getFragmentManager().beginTransaction();
				// fragmentTransaction.replace(R.id.fragment_container,
				// pictureFragment);
				// fragmentTransaction.addToBackStack(null);
				//
				// fragmentTransaction.commit();

				onArticleSelected(10);
			}
		});
	}

	private void setUILang(Locale locale) {
		Resources resources = getResources();

		Configuration config = resources.getConfiguration();
		config.locale = locale;

		DisplayMetrics metrics = resources.getDisplayMetrics();
		
		resources.updateConfiguration(config, metrics);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putCharSequence("MyLove", "Is Your");

		// Always call the superclass so it can save the view hierarchy state
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// only if there is a saved state to restore, so you do not need to
		// check whether the Bundle is null:
		// Always call the superclass so it can restore the view hierarchy
		super.onRestoreInstanceState(savedInstanceState);

		String message = savedInstanceState.getCharSequence("MyLove")
				.toString();
	}

	@Override
	public void onPause() {
		super.onPause();

		// if (mCamera != null) {
		// mCamera.restore();
		// mCamera = null;
		// }
		//
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onStop() {
		super.onStop();

		String message = ((EditText) findViewById(R.id.editTextInput)).getText().toString();

		ContentValues values = new ContentValues();
		values.put(INPUT_MESSAGE, message);

		// getContentResolver().update(uri, values, where, selectionArgs)

		// if (mCamera != null) {
		// mCamera.restore();
		// mCamera = null;
		// }
	}

	@Override
	public void onStart() {
		super.onStart();

		// LocationManager locationManager =
		// (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		// boolean gpsEnabled =
		// locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		// if (!gpsEnabled) {
		//
		// }
	}

	@Override
	public void onRestart() {
		super.onRestart();
	}

	public void onArticleSelected(int position) {
		// TODO Auto-generated method stub
		// The user selected the headline of an article from the ArticleFragment
		// Do something here to display that article
		FragmentManager fragmentManager = getFragmentManager();
		ArticleFragment articleFragment = (ArticleFragment)fragmentManager.findFragmentById(R.id.fragment_container);

		if (articleFragment != null) {
			articleFragment.updateArticleView(position);
		} else {
			Bundle args = new Bundle();
			args.putInt(ArticleFragment.ARG_POSITION, position);
			
			articleFragment = new ArticleFragment();
			articleFragment.setArguments(args);

			// Replace whatever is in the fragment_container view with this
			// fragment,
			// and add the transaction to the back stack so the user can
			// navigate back
			FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
			fragmentTransaction.replace(R.id.fragment_container, articleFragment);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();
		}
	}

}
